<?php
declare (strict_types=1);

namespace addons\BuilderPlus\driver;

use addons\BuilderPlus\components\Button;
use addons\BuilderPlus\components\Column;
use addons\BuilderPlus\components\Search;
use addons\BuilderPlus\facade\Table;
use app\admin\controller\Base;
use app\common\tool\Result;
use think\facade\Cache;
use think\facade\View;
use think\Response;

class Crontab extends Base
{
    public string $path;

    public string $cacheKey = 'BuilderCrontab_';

    public function getOptions(): array
    {
        $this->path = addons_path('BuilderPlus') . '/view/crontab/';

        return [
            'pk' => 'id',
            'url' => url('crontab/getList')->build(),
            'model' => \addons\BuilderPlus\contract\model\Crontab::class,
            'fast' => [
                'add' => $this->path . 'edit.html',
                'save' => '_save',
                'export' => '_export'
            ]
        ];
    }

    public function index(): string
    {
        return Table::init($this)
            ->setCheckbox(false)
            ->addColumns([
                ['id', '任务ID', fn(Column $col) => $col->width(80)],
                ['name', '任务名称'],
                ['tips', '执行周期'],
                ['urladdress', '执行URL'],
                ['addtime', '添加时间', fn(Column $col) => $col->width(150)],
                ['last_time', '上次执行时间', fn(Column $col) => $col->width(150)],
            ])
            ->addTopButtons([
                'add' => fn(Button $btn) => $btn
                    ->title('添加计划任务')
                    ->url(url('crontab/add')->build()),
                'export' => fn(Button $btn) => $btn
                    ->title('导出json文件')
                    ->icon('layui-icon-bot')
                    ->__call('exportUrl', url('crontab/export')->build())
                    ->event('tableExport')
            ])
            ->addRightButtons([
                'execute' => fn(Button $btn) => $btn->title('执行')
                    ->class('warm')
                    ->url(url('crontab/execute')->build())
                    ->event('submit'),
                'record' => fn(Button $btn) => $btn->title('执行记录')
                    ->class('info')
                    ->url(url('crontab/record')->build())
                    ->width('50%')
                    ->event('od')], 180)
            ->addSearch([
                ['name', '任务名称', fn(Search $search) => $search->condition('Like')]
            ])
            ->specifyQuery([['id', '>', 1]])
            ->fetch();
    }

    public function record(): string
    {
        $id = $this->request->get('id');
        $info = $this->getOptions()['model']::where('id', $id)->find();
        $list = Cache::get($this->cacheKey . $info->id);
        if (!empty($list)) {
            $sort = [];
            foreach ($list as &$v) {
                $sort[] = $v['times'];
            }
            array_multisort($sort, SORT_DESC, $list);
        }

        return View::fetch($this->path . 'record.html', ['list' => $list, 'info' => $info]);
    }

    public function execute(): Response
    {
        $param = request()->post();
        $t1 = microtime(true);
        try {
            $info = $this->getOptions()['model']::where('id', $param['id'])->find();
            file_get_contents($info->urladdress);
            $info->last_time = time();
            $info->save();
            $msg = '执行成功';
        } catch (\Exception $e) {
            $msg = '执行失败：' . $e->getMessage();
        }
        $t2 = microtime(true);
        $data['admin'] = request()->admin['admin_name'];
        $data['times'] = time();
        $data['method'] = request()->action();
        $data['ip'] = request()->ip();
        $data['required'] = round($t2 - $t1, 6);
        $data['status'] = $msg;
        $list = Cache::get($this->cacheKey . $info->id);
        $list[] = $data;
        Cache::set($this->cacheKey . $info->id, $list);

        return $msg == '执行成功' ? Result::success($msg) : Result::fail($msg);
    }
}